package com.xb.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xb.entity.Menu;
import com.xb.entity.Tree;
import com.xb.entity.User;
import com.xb.mapper.MenuMapper;
import com.xb.mapper.RoleMenuMapper;
import com.xb.mapper.UserMapper;
import com.xb.service.IMenuService;
import com.xb.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Service业务层处理
 */
@Service
public class MenuServiceImp implements IMenuService {
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;

    /**
     * 分页查询列表
     *
     * @param menu
     * @return
     */
    @Override
    public Result selectMenuList(Menu menu, Integer page, Integer limit) {
        Result result = new Result();
        PageHelper.startPage(page, limit);
        List<Menu> list = menuMapper.selectMenuList(menu);
        PageInfo<Menu> menuPageInfo = new PageInfo<>(list);
        if (menuPageInfo.getList() != null) {
            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setTotal(menuPageInfo.getTotal());
            result.setData(menuPageInfo.getList());
            result.setMessage("查询成功");
        }
        return result;
    }

    @Override
    public Result getMenu(Integer parentId) {
        Result result = new Result();
        result.setData(menuMapper.selectMenuByParentId(parentId));
        return result;
    }

    @Override
    public Result add(Menu menu, HttpSession session) {
        Result result = new Result();
        if (menuMapper.selectMenuByParentIdAndName(menu) != null) {
            result.setMessage("此名称已存在");
            return result;
        }
        String email = (String) session.getAttribute("email");
        User user = userMapper.selectUserByEmail(email);
        menu.setCreateBy(String.valueOf(user.getId()));
        menu.setUrl("#");
        if (menuMapper.insertMenu(menu) > 0) {
            result.setMessage("添加成功！");
            result.setStatus(Result.RESPONSE_SUCCESS);
        } else {
            result.setMessage("添加失败！");
        }
        return result;
    }

    @Override
    public Result update(Menu obj) {
        Result result = new Result();
        Menu menu = menuMapper.selectMenuById(obj.getMenuId());
        if (!menu.getParentId().equals(obj.getParentId()) || !menu.getMenuName().equals(obj.getMenuName())) {
            if (menuMapper.selectMenuByParentIdAndName(obj) != null) {
                result.setMessage("此名称已存在");
                return result;
            }
        }
        if (menuMapper.updateMenu(obj) > 0) {
            result.setMessage("修改成功！");
            result.setStatus(Result.RESPONSE_SUCCESS);
        } else {
            result.setMessage("修改失败！");
        }
        return result;
    }

    @Override
    public Result getMenuTree() {
        Result result = new Result();
        List<Menu> menus = menuMapper.selectAllMenu();
        List<Tree> menuTree = new ArrayList<>();
        List<Tree> menuTrees;
        Tree tree;
        // 一级
        for (int i = 0; i < menus.size(); i++) {
            tree = new Tree();
            if (menus.get(i).getParentId() == 0) {
                tree.setId(menus.get(i).getMenuId());
                tree.setTitle(menus.get(i).getMenuName());
                menuTree.add(tree);
                menus.remove(i);
                i--;
            }
        }
        // 二级
        for (Tree trees : menuTree) {
            menuTrees = new ArrayList<>();
            for (int i = 0; i < menus.size(); i++) {
                if (menus.get(i).getParentId() == trees.getId()) {
                    tree = new Tree();
                    tree.setId(menus.get(i).getMenuId());
                    tree.setTitle(menus.get(i).getMenuName());
                    menuTrees.add(tree);
                    menus.remove(i);
                    i--;
                }
                trees.setChildren(menuTrees);
            }
        }
        // 三级
        for (Tree trees : menuTree) {
            List<Tree> children = trees.getChildren();
            menuTrees = new ArrayList<>();
            for (Tree child : children) {
                for (int i = 0; i < menus.size(); i++) {
                    if (menus.get(i).getParentId() == child.getId()) {
                        tree = new Tree();
                        tree.setId(menus.get(i).getMenuId());
                        tree.setTitle(menus.get(i).getMenuName());
                        menuTrees.add(tree);
                        menus.remove(i);
                        i--;
                    }
                    child.setChildren(menuTrees);
                }
            }
        }

        result.setData(menuTree);
        return result;
    }


    /**
     * 删除信息
     *
     * @param id ID
     * @return 结果
     */
    @Transactional
    @Override
    public Result deleteMenuById(Integer id) {
        Result result = new Result();
        try {
            if (menuMapper.deleteMenuById(id) == 0) {
                throw new IllegalAccessException("菜单删除失败");
            }
            if (!roleMenuMapper.selectRoleMenuByMenuId(id).isEmpty()) {
                if (roleMenuMapper.deleteRoleMenuByMenuId(id) == 0) {
                    throw new IllegalAccessException("角色菜单删除失败");
                }
            }
            result.setMessage("删除成功");
            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage() + "请联系管理员");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
    }

    /**
     * 根据邮箱获取菜单
     *
     * @param email 邮箱
     * @return 集合
     */
    @Override
    public List<Menu> selectMenuByEmail(String email) {
        return menuMapper.selectMenuByEmail(email);
    }
}
